import Vue from 'vue'
import axios from 'axios'
import { Message } from "element-ui"

const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE, // api的base_url
  timeout: 5000 // 请求超时时间
})


service.interceptors.request.use(
  config => {
      let token = '';
      if (token && token !== undefined && token !== "" && token !== "undefined") {
          config.headers['Authorization'] = "Bearer " + token;
      }
      return config;
  },
  error => {
      Promise.reject(error);
  }
);


service.interceptors.response.use(
  response => {
      const res = response.data;
      if(res.code === 401) {
          //尚未登录
          this.$router.push('/');
      }
      if (res.code != "0") {
          Message({
              message: res.message,
              type: 'error',
              duration: 5 * 1000
          });
          return Promise.resolve(res);
      } else {
          return res;
      }
  },
  () => {
      return Promise.resolve({ data: [] });
  }
);

Vue.prototype.axios = service

export default service